<template>
	<view class="container">
		<view class="inputBox">
			<u--form :model="form" labelPosition="left">
				<u-form-item>
					<view class="avatorBox">
						<u-image src="/static/logo.png" :fade="false" shape="circle" width="80px"
							height="80px"></u-image>
					</view>
				</u-form-item>
				<u-form-item prop="userInfo.name" ref="item1">
					<u--input v-model="form.userNo" required placeholder="输入ID(3位数字)" maxlength="3" inputAlign="center"
						clearable border="bottom"></u--input>
				</u-form-item>
				<u-form-item prop="userInfo.name" ref="item1">
					<u--input v-model="form.userName" placeholder="输入用户名(10位以内)" maxlength="10" inputAlign="center"
						clearable border="bottom"></u--input>
				</u-form-item>
				<u-form-item>
					<u-button text="登录" color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"
						@click="handleSubmit">
					</u-button>
				</u-form-item>
			</u--form>
		</view>

	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue'

	let form = ref({
		userNo: '',
		userName: ''
	})

	const ddzUser = uniCloud.importObject('ddz-user')
	onMounted(async () => {
		// ddzUser.delUser()
		let user = uni.getStorageSync('user')
		if (user) {
			form.value.userNo = user.userNo
			form.value.userName = user.userName
		}
	})

	const handleSubmit = async () => {
		// 登录事件
		// console.log(form.value);
		const res = await ddzUser.checkUser(form.value)
		console.log('checkUser',res);
		if (res.data) {
			// 存在用户 直接登录
			const res1 = await ddzUser.loginUser(res.data._id)
			console.log('loginUser',res1);
			if (res1.code == 200) {
				uni.setStorageSync('user', res.data)
				uni.setStorageSync('score', res1.data)
				uni.redirectTo({
					url: '/pages/index/index'
				})
			}
		} else {
			// 不存在用户 询问新建
			uni.showModal({
				title: '用户不存在，是否新建？',
				content: `ID： ${form.value.userNo}， 昵称： ${form.value.userName}`,
				confirmText: '是',
				cancelText: '否',
				async success(res) {
					// console.log(res);
					if (res.confirm) {
						const res1 = await ddzUser.addUser({
							...form.value
						})
						if (res1.code == 200) {
							handleSubmit()
						}
					}
				}
			})
		}

	}
</script>

<style lang="scss" scoped>
	.container {
		width: 100vw;
		height: 100vh;
		position: relative;
	}

	.inputBox {
		width: 50%;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);

		.avatorBox {
			width: 80px;
			height: 80px;
			margin: auto;
		}
	}
</style>